package com.fintech.pangu.apollo.autorefresh;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.fintech.pangu.apollo.annotation.AutoRefresh;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Description:
 */
public class AutoRefreshConfig implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    private Map<String, AutoRefresh> autoRefreshBeans = new HashMap<String, AutoRefresh>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @ApolloConfigChangeListener
    public void onChange(ConfigChangeEvent changeEvent) {
        if (autoRefreshBeans.size() > 0){
            Set<String> keySet = new HashSet<String>();
            for (Map.Entry<String,AutoRefresh> entry : autoRefreshBeans.entrySet()){
                for (String changedKey : changeEvent.changedKeys()) {
                    if (changedKey.startsWith(entry.getValue().prefix())) {
                        keySet.add(entry.getKey());
                        break;
                    }
                }
            }
            if (keySet.size() > 0){
                this.applicationContext.publishEvent(new AutoRefreshChangeEvent(keySet));
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String[] beanNames = applicationContext.getBeanNamesForType(Object.class);
        for (String beanName : beanNames) {
            Class clazz = applicationContext.getType(beanName);
            AutoRefresh autoRefresh = AnnotationUtils.findAnnotation(clazz, AutoRefresh.class);
            if (null != autoRefresh) {
                autoRefreshBeans.put(beanName,autoRefresh);
            }
        }
    }
}
